<template>
	<view class="container">
		
		<view class="shabao">
			<view class="myHeader">
				<u-icon name="account" color="#473E97" size="30" @click="goToUserInfo"></u-icon>
			</view>
			<view class="" v-if="shabao.id!=''">
				<u-row>
					<u-col span="4">
						<u--image :showLoading="true" :src="shabaoImg" width="120px" height="120px" @click="click"></u--image>
					</u-col>
					<u-col span="8">
						<u-cell-group :border="border">
							<u-cell :border="border" icon="integral-fill" title="编号" :value="shabao.id"></u-cell>
							<u-cell :border="border" icon="integral-fill" title="重量" :value="shabao.weight"></u-cell>
							<u-cell :border="border" icon="integral-fill" title="填充" :value="shabao.inside"></u-cell>
						</u-cell-group>
					</u-col>
				</u-row>
			</view>
			<view class="scanButton" v-else>
				<u-button type="error" icon="scan"
				:plain="true" text="扫码绑定沙袋"
				@click="scanCode"></u-button>
			</view>
		</view>
		<view class="train_data">
			<u-row justify="space-between">
				<u-col span="6">
					<view class="demo-layout bg-orange" @click="batchList">
						<view class="card-head">
							训练次数
						</view>
						<view v-if="userInfo._id" class="card-body">
							{{fightCount}}
						</view>
					</view>
				</u-col>
				<u-col span="6">
					<view class="demo-layout bg-death">
						<view class="card-head">
							卡路里
						</view>
						<view class="card-body">
							{{calorie}}
						</view>
					</view>
				</u-col>
			</u-row>
			<u-row justify="space-between">
				<u-col span="4">
					<view class="demo-layout bg-green">
						<view class="card-head">
							最小值
						</view>
						<view class="card-body">
							{{minFight}}
						</view>
					</view>
				</u-col>
				<u-col span="4">
					<view class="demo-layout bg-blue">
						<view class="card-head">
							平均值
						</view>
						<view class="card-body">
							{{averageFight}}
						</view>
					</view>
				</u-col>
				<u-col span="4">
					<view class="demo-layout bg-purple">
						<view class="card-head">
							最大值
						</view>
						<view class="card-body">
							{{maxFight}}
						</view>
					</view>
				</u-col>
			</u-row>
		</view>
		
		<view class="action">
			<view class="button" @click="actionButtonClick">
				{{actionText}}
			</view>
		</view>
	</view>
</template>

<script>
	import { WSNRTConnect } from '@/static/WSN/WSNRTConnect.js'
	const db = uniCloud.database()
	import {
	  store,
	  mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	
	export default {
		computed: {
			userInfo() {
				return store.userInfo 
			}
		},
		watch: {
			userInfo() {
				db.collection("batch").where({
					user_id: this.userInfo._id
				}).count().then((res)=>{
					this.fightCount = res.result.total
				})
			},
			train_data() {
				let total = 0
				this.train_data.forEach((item) => {
					total += item
				})
				this.calorie = parseInt(total * 0.239)
				this.maxFight = parseInt(Math.max.apply(null,this.train_data)) 
				this.minFight = parseInt(Math.min.apply(null,this.train_data)) 
				this.averageFight = parseInt(total / this.train_data.length)
			}
		},
		data() {
			return {
				border: false,
				shabaoImg: "/static/shadai.png",
				shabao:{
					id:"",
					Dmac:"",
					weight: "",
					inside: ""
				},
				fightCount: 0,
				calorie: 0,
				maxFight: 0,
				minFight: 0,
				averageFight: 0,
				actionText: "开始",
				actionStatus: false,
				start_time: 0,
				batch_id:"",
				train_data: [],
				id: "729361770710",                                //智云帐号
				key: "VFdaVVBTAQcHU1IFYFtXV1lGRGo",              //智云密钥
				addr: "api.zhiyun360.com",                      //智云服务器地址
				// DemoMac:'',
				mac:'',
				// mac: '01:12:4B:00:49:38:B4:62',					//节点地址
				rtc: null,										//创建用户数据服务对象
				state: '数据服务连接失败...',					//服务连接状态
				temp: 0,										//温度
				humi: 0,										//湿度
				switchVal: false,								//开关
			}
		},
		onLoad() {
			// this.getConnect()							 		//与智云服务连接，并监听和解析实时数据并显示
		},
		methods: {
			/*********************************************************************************************
			* 与智云服务连接，并监听和解析实时数据并显示
			*********************************************************************************************/  
			getConnect(){       
				this.rtc = new WSNRTConnect(this.id, this.key)  //创建数据连接服务对象
				this.rtc.setServerAddr(this.addr)               //设置服务器地址
				this.rtc.connect()                              //数据推送服务连接
				this.rtc.onConnect = () => {                    //连接成功回调函数
					this.state = '数据服务连接成功...'
					console.log('数据服务连接成功...')
					console.log(this.mac)
					this.rtc.sendMessage(this.mac, '{A1=?,A2=?,D1=?}')    //查询温湿度、灯光初始值
				}
				this.rtc.onConnectLost = () => {                //数据服务掉线回调函数
					console.log('数据服务连接失败...')
					this.state = '数据服务连接失败...'
				};
				this.rtc.onmessageArrive = (mac, data) => {     //消息处理回调函数
					if (data[0] == '{' && data[data.length - 1] == '}') {     
						let its = data.slice(1,-1).split(',')   //将后台返回的json对象截取（去掉{}符号）后以“,”分割为数组
						for (let i = 0; i < its.length; i++) {  //循环遍历数组的每一个值
							let t = its[i].split("=")           //将每个值以“=”分割为数组t[0]为参t[1]为值
							if (t.length != 2) continue		    //满足条件时结束当前循环
							console.log({mac},its);
							if (mac == this.mac) {				//判断是否是节点的数据
								if (t[0] == 'A3') {          	//判断参数A1
									console.log(t[1])
									let canshu = parseInt(t[1]) 
									console.log(canshu)
									this.train_data.push(canshu)
									console.log(this.train_data)
								}
							}
						}
					}
				}
			},
			// MyDisconnect(){
			// 	this.rtc = new WSNRTConnect(this.id, this.key)  //创建数据连接服务对象
			// 	this.rtc.setServerAddr(this.addr)               //设置服务器地址
			// 	this.rtc.disconnect()//断开连接
			// },
			// jisuan(){
			// 	console.log("开始计算")
			// 	let total = 0
			// 	this.train_data.forEach((item) => {
			// 		total += item
			// 	})
			// 	this.calorie = total * 0.239
			// 	this.maxFight = Math.max(this.train_data)
			// 	this.minFight = Math.min(this.train_data)
			// 	this.averageFight = parseInt(total / this.train_data.length)
			// 	console.log("计算结束")
			// },
			goToUserInfo(){
				uni.navigateTo({
					url:"/uni_modules/uni-id-pages/pages/userinfo/userinfo"
				})
			},
			scanCode(){
				if(this.userInfo._id){
					var that = this
					uni.scanCode({
						onlyFromCamera: true,
						success: function (res) {
							console.log('条码类型：' + res.scanType);
							console.log('条码内容：' + res.result);
							let shaobao_data = JSON.parse(res.result)
							// console.log(shaobao_data)
							// console.log(shaobao_data.mac)
							that.shabao = shaobao_data
							// console.log(that.shabao.mac)
							that.mac = that.shabao.Dmac
							console.log(that.mac)
						}
					});
				}else{
					uni.navigateTo({
						url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
					});
				}
			},
			batchList(){
				uni.navigateTo({
					url:"/pages/batch/list?user_id="+this.userInfo._id
				})
			},
			getDataFromZonesion(){
				
			},
			actionButtonClick(){
				var that = this
				if(!this.actionStatus){
					if(this.shabao.id == "") {
						uni.showModal({
							title:"出错",
							content:"请先扫码绑定沙袋",
							showCancel:false
						})
					}else{
						db.collection("batch").add({
							"user_id": this.userInfo._id,
							"shabao": this.shabao,
							"start_time": new Date().getTime()
						}).then((res)=>{
							that.batch_id = res.result.id
							console.log(that.batch_id)
							this.getConnect()
							uni.showToast({
								title: "训练开始",
								duration: 1000
							})
							this.actionStatus = true
							this.actionText = "结束"
						})
					}
				} else {
					uni.showModal({
						title:"提醒",
						content: "确定要结束训练吗？",
						success:function(res){
							if(res.confirm){
								// 用户结束训练，将数据更新到数据库中
								db.collection("batch").doc(that.batch_id)
								.update({
									end_time: new Date().getTime(),
									datas: that.train_data,
									calorie: that.calorie
								}).then((res)=>{
									console.log(res)
									that.rtc.disconnect();
									that.calorie = 0
									that.maxFight = 0
									that.minFight = 0
									that.averageFight=0
									that.fightCount = that.fightCount + 1
								})
							}
						}
					})
					// console.log("开始断开连接")
					// this.MyDisconnect();
					// console.log("连接已经成功断开")
					// this.jisuan();
				}
			}
		}
	}
</script>

<style scoped>
	
	.container{
		display: flex;
		flex-direction: column;
		background-color: #473E97;
		height: 100vh;
	}
	.shabao{
		display: flex;
		height: 200px;
		flex-direction: column;
		margin: 0;
		background-color: #FFFFFF;
		border-bottom-left-radius: 20px;
		border-bottom-right-radius:20px;
	}	
	.myHeader{
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		height: 40px;
		padding: 5px 10px 2px;
		margin: 0;
	}
	.shabaoImg{
		width: 60px;
		height: 60px;
	}
	.scanButton{
		margin: 20px 80px 0;
	}
	.train_data{
		flex: 3;
		margin: 20px 10px 0;
	}
	.wrap {
		padding: 12px;
	}
	.demo-layout {
		height: 100px;
		margin: 10px;
		
		border-radius: 6px;
		color: #FFFFFF;
		font-weight: bold;
	}
	.card-head{
		font-size: 16px;
		padding: 5px;
	}
	.card-body{
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 10px;
		font-size: 30px;
	}
	.bg-orange {
		background: #FFB25A;
	}

	.bg-death {
		background: #FF5959;
	}

	.bg-blue {
		background: #4BB6FE;
	}
	.bg-green {
		background: #4ADA7B;
	}
	.bg-purple{
		background: #9059FF;
	}
	.action{
		display: flex;
		flex: 1;
		align-items: center;
		justify-content: center;
		margin: 10px;
	}
	.button{
		height: 80px;
		width: 80px;
		text-align: center;
		line-height: 80px;
		color: #FFFFFF;
		font-size: 20px;
		font-weight: bold;
		border-radius: 44px;
		border: 4px solid #FFFFFF;
		background-color: #4D79FF;
	}
</style>
